package com.xaptul.docpreview.util.converter;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.commons.lang.StringEscapeUtils;
import org.mozilla.universalchardet.UniversalDetector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.xaptul.docpreview.util.abstra.Converter;
import com.xaptul.docpreview.util.exception.ConvertException;

@Supported({ "*.txt" })
public class TextConverter implements Converter {
	private Logger logger = LoggerFactory.getLogger(TextConverter.class);

	private UniversalDetector[] detectors = { new UniversalDetector(null),
			new UniversalDetector(null), new UniversalDetector(null),
			new UniversalDetector(null) };

	/**
	 * 获取文件编码
	 * @param infile
	 * @return
	 */
	private String detectEncoding(File infile) {
		InputStream in = null;
		try {
			in = new FileInputStream(infile);
			UniversalDetector detector = this.detectors[(0x3 & in.hashCode())];
			synchronized (detector) {
				detector.reset();
				byte[] buf = new byte['ÿ'];
				int idx;
				while ((idx = in.read(buf)) > 0) {
					detector.handleData(buf, 0, idx);
					if (detector.isDone())
						break;
				}
				detector.dataEnd();
				String charset = detector.getDetectedCharset();
				String str1 = charset == null ? "utf8" : charset;

				if (in != null)
					try {
						in.close();
					} catch (IOException localIOException1) {
					}
				return str1;
			}
		} catch (IOException e) {
			this.logger.error(e.getMessage(), e);
		} finally {
			if (in != null)
				try {
					in.close();
				} catch (IOException localIOException3) {
				}
		}
		return "utf8";
	}

	public void convert(File infile, File outfile) throws ConvertException {
		if (outfile.exists())
			return;
		File outdir = outfile.getParentFile();
		if (!outdir.exists())
			outdir.mkdirs();

		FileWriter fileWriter = null;
		BufferedReader fileReader = null;
		try {
			InputStream in = new FileInputStream(infile);
			fileReader = new BufferedReader(new InputStreamReader(in,
					detectEncoding(infile)));
			fileWriter = new FileWriter(outfile);
			fileWriter.write("<!DOCTYPE html>\n");
			fileWriter.write("<html>\n");
			fileWriter
					.write("<head><meta HTTP-EQUIV=CONTENT-TYPE CONTENT=\"text/html; charset=utf-8\"></head>\n");
			fileWriter.write("<body>\n");
			fileWriter.write("<pre>\n");
			String line;
			while ((line = fileReader.readLine()) != null) {
				StringEscapeUtils.escapeHtml(fileWriter, line);
				fileWriter.write("\n");
			}
			fileWriter.write("</pre>\n");
			fileWriter.write("</body>\n");
			fileWriter.write("</html>\n");
		} catch (IOException e) {
			throw new ConvertException(e);
		} finally {
			if (fileWriter != null)
				try {
					fileWriter.close();
				} catch (IOException e) {
					this.logger.error(e.getMessage(), e);
				}
			if (fileReader != null)
				try {
					fileReader.close();
				} catch (IOException e) {
					this.logger.error(e.getMessage(), e);
				}
			try {
				//infile.delete();
			} catch (Exception localException) {
				this.logger.error(localException.getMessage(), localException);
			}
		}
	}
}